package all.com.jinyongqunxiax.utility;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class JxThreadPool {
    private static JxThreadPool       shared;
    private        ThreadPoolExecutor pool;

    private JxThreadPool() {
        int                     processors = Runtime.getRuntime().availableProcessors();
        BlockingQueue<Runnable> queue      = new LinkedBlockingQueue<>();
        ThreadFactory factory = new ThreadFactory() {
            int threadCount = 0;

            @Override
            public synchronized Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                if (r instanceof JxThreadRunable) {
                    thread.setName(((JxThreadRunable) r).name() + "#" + threadCount);
                } else {
                    thread.setName("thread#" + threadCount);
                }
                threadCount++;
                return thread;
            }
        };
        pool = new ThreadPoolExecutor(processors, processors * 2, processors * 2, TimeUnit.MILLISECONDS, queue/*, factory*/);
    }

    public static JxThreadPool shared() {
        return Singleton.shared;
    }

    public synchronized void post(JxThreadRunable runnable) {
        pool.execute(runnable);
    }

    public void finish() {
        pool.shutdown();
    }

    public interface JxThreadRunable extends Runnable {
        String name();
    }

    private static class Singleton {
        static volatile JxThreadPool shared = new JxThreadPool();
    }
}
